package com.dminvoicemanager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;

public class DM_InvoiceLoading extends Activity {

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String TEMP_USER = "invtempuser";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Loading
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";
	private SQLiteDatabase mydb;
	JSONArray jArray, jArrayp;
	String result = null;
	String resultp = null;
	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	StringBuilder sbp = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_loading);

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {

			/*
			 * mydb.execSQL("DROP TABLE IF EXISTS invtempuser");
			 * mydb.execSQL("DROP TABLE IF EXISTS fArea");
			 * mydb.execSQL("DROP TABLE IF EXISTS fCompanySetting");
			 * mydb.execSQL("DROP TABLE IF EXISTS fControl");
			 * mydb.execSQL("DROP TABLE IF EXISTS fDebtor");
			 * mydb.execSQL("DROP TABLE IF EXISTS fItemLoc");
			 * mydb.execSQL("DROP TABLE IF EXISTS fLocation");
			 * mydb.execSQL("DROP TABLE IF EXISTS fItemPri");
			 * mydb.execSQL("DROP TABLE IF EXISTS fItems");
			 * mydb.execSQL("DROP TABLE IF EXISTS FCompanyBranch");
			 * mydb.execSQL("DROP TABLE IF EXISTS fSalRep");
			 */

			// Main Invoice

			/*
			 * mydb.execSQL("DROP TABLE IF EXISTS frepInvoiceSumery");
			 * mydb.execSQL("DROP TABLE IF EXISTS FinvDet");
			 * mydb.execSQL("DROP TABLE IF EXISTS FinvHed");
			 * 
			 * // Stock Loading
			  mydb.execSQL("DROP TABLE IF EXISTS frepStockLoadingSummary");
			  mydb.execSQL("DROP TABLE IF EXISTS fLoadhed");
			  mydb.execSQL("DROP TABLE IF EXISTS fLoadDet");
			 */
			/* mydb.execSQL("DROP TABLE IF EXISTS FOrdHed"); */
			
			mydb.execSQL("create table if not exists "
					+ TEMP_USER
					+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_AREA
					+ "(farea_id integer primary key autoincrement,AreaCode text not null,AreaName text not null,RegCode text not null,DealCode text not null,AddUser text not null,AddDatefarea text not null,AddMach text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_REP_INVOICESUMERY
					+ "(remprepinv_id integer primary key autoincrement,repusername text not null,repprefix text not null,tempRepInvNoCode text not null,tempRepInvSerial text not null,invoiceComplete text not null,activeInvoice text not null,activeInvoiceValue text not null,activeInvItemDiscount text not null,activeInvCusDiscount text not null,activeInvCusDiscountValue text not null,InvoiceCustomerCode text not null,InvoiceCustomerName text not null,InvoiceSynchState text not null,recordDate text not null,recordSynchDate text not null,invlateststate text not null,activeInvoiceReturnValue text not null,activeInvoiceRemarks text not null,invoiceNoOfItems text not null,invoiceRef text not null,invoiceRefStl text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOCATION
					+ "(flocation_id integer primary key autoincrement,AddMach text not null,AddUser text not null,Address1 text not null,Address2 text not null,Address3 text not null,Contact text not null,EMail text not null,FaxNo text not null,LocCode text not null,LocName text not null,LoctCode text not null,RecordId text not null,RepCode text not null,TeleNo text not null,LocAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEMS
					+ "(fitem_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,MapCode text not null,ItemName text not null,VenPcode text not null,GroupCode text not null,TypeCode text not null,TaxComCode text not null,UnitCode text not null,SkuSizCode text not null,ItemStatus text not null,ReOrderLvl text not null,ReOrderQty text not null,AvgPrice text not null,PurAcc text not null,PurRetAcc text not null,SVATAcc text not null,ExportAcc text not null,IndrExAcc text not null,SalAcc text not null,SalRetAcc text not null,DisAcc text not null,ClsStkAcc text not null,StkInAcc text not null,PrilCode text not null,BrandCode text not null,SBrandCode text not null,NOUCase text not null,OrdSeq text not null,AddUser text not null,AddDatefitem text not null,AddMach text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_PRICE
					+ "(fitempri_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,PrilCode text not null,PriRDate text not null,Price text not null,AddUser text not null,AddDateIP text not null,AddMach text not null,Txnuser text not null,TxnDate text not null,TxnMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOC_DETAILS
					+ "(flocdet_id integer primary key autoincrement,LocCode text not null,ItemCode text not null,QOH text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_DEBTOR
					+ "(fdebtor_id integer primary key autoincrement,DebCode text not null,DebName text not null,DebAdd1 text not null,DebAdd2 text not null,DebAdd3 text not null,DebTele text not null,DebMob text not null,DebEMail text not null,CretDate text not null,OutDis text not null,RemDis text not null,TownCode text not null,AreaCode text not null,DebCatCode text not null,DbGrCode text not null,DebClsCode text not null,Status text not null,DebLylty text not null,DealCode text not null,AddUser text not null,AddDateDEB text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,CrdPeriod text not null,ChkCrdPrd text not null,CrdLimit text not null,ChkCrdLmt text not null,RepCode text not null,RankCode text not null,txndate text not null,TranBatch text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_CONTROL
					+ "(fcontrol_id integer primary key autoincrement,ComName text not null,ComAdd1 text not null,ComAdd2 text not null,ComAdd3 text not null,comtel1 text not null,comtel2 text not null,comfax1 text not null,comemail text not null,comweb text not null,confyear text not null,contyear text not null,comRegNo text not null,ConfTxn text not null,ContTxn text not null,Crystalpath text not null,VatCmTaxNo text not null,NbtCmTaxNo text not null,SysId text not null,DealCode text not null,basecur text not null,BalgCrLm text not null,conage1 text not null,conage2 text not null,conage3 text not null,conage4 text not null,conage5 text not null,conage6 text not null,conage7 text not null,conage8 text not null,conage9 text not null,conage10 text not null,conage11 text not null,conage12 text not null,conage13 text not null,conage14 text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_COMPANY_SETTING
					+ "(fcomset_id integer primary key autoincrement,cSettingsCode text not null,cSettingGrp text not null,cLocationChar text not null,cCharVal text not null,nNumVal text not null,cRemarks text not null,nType text not null,bUpdateFlag text not null,cCompanyCode text not null,recordid text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_DETAILS
					+ "(invdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,Itemcode text not null,Txnseqno text not null,SellPrice text not null,BSellPrice text not null,TSellPrice text not null,BTSellPrice text not null,CostPrice text not null,CaseQty text not null,Type text not null,PiceQty text not null,Qty text not null,BalQty text not null,DisPer text not null,DisAmt text not null,BDisAmt text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,ReaCode text not null,Linkrec text not null,RecordId text not null,itemDescription text not null,refInvoiceDetNo text not null,refInvoiceDetCode text not null,refInvitemCaseQty text not null,refInvStockOrderNo text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_HEADER
					+ "(invhead_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,InvType text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,RepCode text not null,AreaCode text not null,RouteCode text not null,DebCode text not null,LocCode text not null,Remarks text not null,CostCode text not null,CurCode text not null,CurRate text not null,TxnType text not null,InvAmt text not null,OutDis text not null,InvDis text not null,TotMkrAmt text not null,UnOvAmt text not null,TotalDis text not null,TotalAmt text not null,AddUser text not null,AddDateInvHead text not null,AddMach text not null,prtcopy text not null,RecordId text not null,timestamp_column text not null,refInvoiceHeaderNo text not null,refInvoiceHeaderCode text not null);");

			// Stock Loading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEAD
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAIL
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARY
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_COMPANY_BRANCH
					+ "(fcombra_id integer primary key autoincrement,BranchCode text not null,RecordId text not null,cSettingsCode text not null,nNumVal text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_SAL_REP
					+ "(fsalrep_id integer primary key autoincrement,ASECode text not null,AreaCode text not null,DealCode text not null,RecordId text not null,RepCode text not null,RepPrefix text not null,RepTCode text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_HEAD
					+ "(stohed_id integer primary key autoincrement,AddMach text not null,AddUser text not null,AreaCode text not null,CostCode text not null,CurCode text not null,CurRate text not null,DealCode text not null,DebCode text not null,InvAmt text not null,InvDis text not null,InvFlg text not null,LocCode text not null,ManuRef text not null,OutDis text not null,RecordId text not null,RefNo text not null,Remarks text not null,RepCode text not null,RouteCode text not null,TotMkrAmt text not null,TotalAmt text not null,TotalDis text not null,TranBatch text not null,TxnType text not null,UnOvAmt text not null,prtcopy text not null,TxnDate text not null,stOrderComplete text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_DETAIL
					+ "(stodet_id integer primary key autoincrement,Amt text not null,BAmt text not null,BDisAmt text not null,BSellPrice text not null,BTSellPrice text not null,BTaxAmt text not null,BalQty text not null,CaseQty text not null,CostPrice text not null,DisAmt text not null,DisPer text not null,Itemcode text not null,PiceQty text not null,Qty text not null,ReaCode text not null,RecordId text not null,RefNo text not null,SellPrice text not null,SeqNo text not null,TSellPrice text not null,TaxAmt text not null,TxnType text not null,Txnseqno text not null,Type text not null,TxnDate text not null);");

			// Stock UnLoading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYUN
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			// Stock Damage
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYDAM
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

		} catch (Exception e) {
		}

		Cursor items = null;
		Cursor debtors = null;
		try {
			items = mydb.query(ITEMS, null, null, null, null, null, null);
		} catch (Exception e) {
		}
		try {
			debtors = mydb.query(ITEM_DEBTOR, null, null, null, null, null,
					null);
		} catch (Exception e) {
		}
		if (items == null || debtors == null) {
			new DownloadAdministrative().execute();
		} else if (items.getCount() < 1 || debtors.getCount() < 1) {
			new DownloadAdministrative().execute();
		} else {

			Intent intentDirectLog = new Intent(getBaseContext(),
					DM_InvoiceMainActivity.class);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentDirectLog);
			mydb.close();
			finish();
			return;
		}

		new DownloadAdministrative().execute();
		// new DownloadAdministrativeTesting().execute();
	}

	private class DownloadAdministrativeTesting extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceLoading.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			// *****************Download FOrdHed**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/FOrdHed/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfstordhed = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstordhed.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("FOrdHedResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String AreaCode = jObject.getString("AreaCode");
					String CostCode = jObject.getString("CostCode");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DealCode = jObject.getString("DealCode");
					String DebCode = jObject.getString("DebCode");
					String InvAmt = jObject.getString("InvAmt");
					String InvDis = jObject.getString("InvDis");
					String InvFlg = jObject.getString("InvFlg");
					String LocCode = jObject.getString("LocCode");
					String ManuRef = jObject.getString("ManuRef");
					String OutDis = jObject.getString("OutDis");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String TotMkrAmt = jObject.getString("TotMkrAmt");
					String TotalAmt = jObject.getString("TotalAmt");
					String TotalDis = jObject.getString("TotalDis");
					String TranBatch = jObject.getString("TranBatch");
					String TxnType = jObject.getString("TxnType");
					String UnOvAmt = jObject.getString("UnOvAmt");
					String prtcopy = jObject.getString("prtcopy");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstordhed = new ContentValues();
					Cursor cursorfstordhed = null;
					try {
						cursorfstordhed = mydb.query(STOCK_ORDER_HEAD, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (cursorfstordhed == null) {
						newrowfstordhed.put("AddMach", AddMach.trim());
						newrowfstordhed.put("AddUser", AddUser.trim());
						newrowfstordhed.put("AreaCode", AreaCode.trim());
						newrowfstordhed.put("CostCode", CostCode.trim());
						newrowfstordhed.put("CurCode", CurCode.trim());
						newrowfstordhed.put("CurRate", CurRate.trim());
						newrowfstordhed.put("DealCode", DealCode.trim());
						newrowfstordhed.put("DebCode", DebCode.trim());
						newrowfstordhed.put("InvAmt", InvAmt.trim());
						newrowfstordhed.put("InvDis", InvDis.trim());
						newrowfstordhed.put("InvFlg", InvFlg.trim());
						newrowfstordhed.put("LocCode", LocCode.trim());
						newrowfstordhed.put("ManuRef", ManuRef.trim());
						newrowfstordhed.put("OutDis", OutDis.trim());
						newrowfstordhed.put("RecordId", RecordId.trim());
						newrowfstordhed.put("RefNo", RefNo.trim());
						newrowfstordhed.put("Remarks", Remarks.trim());
						newrowfstordhed.put("RepCode", RepCode.trim());
						newrowfstordhed.put("RouteCode", RouteCode.trim());
						newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
						newrowfstordhed.put("TotalAmt", TotalAmt.trim());
						newrowfstordhed.put("TotalDis", TotalDis.trim());
						newrowfstordhed.put("TranBatch", TranBatch.trim());
						newrowfstordhed.put("TxnType", TxnType.trim());
						newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
						newrowfstordhed.put("prtcopy", prtcopy.trim());
						newrowfstordhed.put("TxnDate", TxnDate.trim());
						newrowfstordhed.put("stOrderComplete", "0");
						mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
						cursorfstordhed.close();
						mydb.close();
					} else if (cursorfstordhed.getCount() < 1) {
						newrowfstordhed.put("AddMach", AddMach.trim());
						newrowfstordhed.put("AddUser", AddUser.trim());
						newrowfstordhed.put("AreaCode", AreaCode.trim());
						newrowfstordhed.put("CostCode", CostCode.trim());
						newrowfstordhed.put("CurCode", CurCode.trim());
						newrowfstordhed.put("CurRate", CurRate.trim());
						newrowfstordhed.put("DealCode", DealCode.trim());
						newrowfstordhed.put("DebCode", DebCode.trim());
						newrowfstordhed.put("InvAmt", InvAmt.trim());
						newrowfstordhed.put("InvDis", InvDis.trim());
						newrowfstordhed.put("InvFlg", InvFlg.trim());
						newrowfstordhed.put("LocCode", LocCode.trim());
						newrowfstordhed.put("ManuRef", ManuRef.trim());
						newrowfstordhed.put("OutDis", OutDis.trim());
						newrowfstordhed.put("RecordId", RecordId.trim());
						newrowfstordhed.put("RefNo", RefNo.trim());
						newrowfstordhed.put("Remarks", Remarks.trim());
						newrowfstordhed.put("RepCode", RepCode.trim());
						newrowfstordhed.put("RouteCode", RouteCode.trim());
						newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
						newrowfstordhed.put("TotalAmt", TotalAmt.trim());
						newrowfstordhed.put("TotalDis", TotalDis.trim());
						newrowfstordhed.put("TranBatch", TranBatch.trim());
						newrowfstordhed.put("TxnType", TxnType.trim());
						newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
						newrowfstordhed.put("prtcopy", prtcopy.trim());
						newrowfstordhed.put("TxnDate", TxnDate.trim());
						newrowfstordhed.put("stOrderComplete", "0");
						mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
						cursorfstordhed.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfstordhed.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			Intent intentLogin = new Intent(getBaseContext(),
					DM_InvoiceMainActivity.class);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentLogin);
			finish();
			return;

		}

	}

	// DownloadJSON AsyncTask
	private class DownloadAdministrative extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceLoading.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// *****************Download fItemLoc**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fItemLoc/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfItemLoc = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItemLoc.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fItemLocResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String LocCode = jObject.getString("LocCode");
					String ItemCode = jObject.getString("ItemCode");
					String QOH = jObject.getString("QOH");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfitemloc = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(ITEM_LOC_DETAILS, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (adminuserrows == null) {
						newrowfitemloc.put("LocCode", LocCode.trim());
						newrowfitemloc.put("ItemCode", ItemCode.trim());
						newrowfitemloc.put("QOH", QOH.trim());
						newrowfitemloc.put("RecordId", RecordId.trim());
						newrowfitemloc.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_LOC_DETAILS, null, newrowfitemloc);
						adminuserrows.close();
						mydb.close();
					} else if (adminuserrows.getCount() < 1) {
						newrowfitemloc.put("LocCode", LocCode.trim());
						newrowfitemloc.put("ItemCode", ItemCode.trim());
						newrowfitemloc.put("QOH", QOH.trim());
						newrowfitemloc.put("RecordId", RecordId.trim());
						newrowfitemloc.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_LOC_DETAILS, null, newrowfitemloc);
						adminuserrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfItemLoc.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItemPri**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fItemPri/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfItemPri = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItemPri.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fItemPriResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String PrilCode = jObject.getString("PrilCode");
					String Price = jObject.getString("Price");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String Txnuser = jObject.getString("Txnuser");
					String TxnMach = jObject.getString("TxnMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemPri = new ContentValues();
					Cursor newrowfItemPriuserrows = null;
					try {
						newrowfItemPriuserrows = mydb.query(ITEM_PRICE, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (newrowfItemPriuserrows == null) {
						newrowfItemPri.put("SKUCode", SKUCode.trim());
						newrowfItemPri.put("ItemCode", ItemCode.trim());
						newrowfItemPri.put("PrilCode", PrilCode.trim());
						newrowfItemPri.put("PriRDate", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("Price", Price.trim());
						newrowfItemPri.put("AddUser", AddUser.trim());
						newrowfItemPri.put("AddDateIP", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("AddMach", AddMach.trim());
						newrowfItemPri.put("Txnuser", Txnuser.trim());
						newrowfItemPri.put("TxnDate", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("TxnMach", TxnMach.trim());
						newrowfItemPri.put("RecordId", RecordId.trim());
						mydb.insert(ITEM_PRICE, null, newrowfItemPri);
						newrowfItemPriuserrows.close();
						mydb.close();
					} else if (newrowfItemPriuserrows.getCount() < 1) {
						newrowfItemPri.put("SKUCode", SKUCode.trim());
						newrowfItemPri.put("ItemCode", ItemCode.trim());
						newrowfItemPri.put("PrilCode", PrilCode.trim());
						newrowfItemPri.put("PriRDate", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("Price", Price.trim());
						newrowfItemPri.put("AddUser", AddUser.trim());
						newrowfItemPri.put("AddDateIP", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("AddMach", AddMach.trim());
						newrowfItemPri.put("Txnuser", Txnuser.trim());
						newrowfItemPri.put("TxnDate", getCurrentTimeString()
								.toString());
						newrowfItemPri.put("TxnMach", TxnMach.trim());
						newrowfItemPri.put("RecordId", RecordId.trim());
						mydb.insert(ITEM_PRICE, null, newrowfItemPri);
						newrowfItemPriuserrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfItemPri.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItems**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fItems/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfItems = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItems.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse.getJSONArray("fItemsResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String MapCode = jObject.getString("MapCode");
					String ItemName = jObject.getString("ItemName");
					String VenPcode = jObject.getString("VenPcode");
					String GroupCode = jObject.getString("GroupCode");
					String TypeCode = jObject.getString("TypeCode");
					String TaxComCode = jObject.getString("TaxComCode");
					String UnitCode = jObject.getString("UnitCode");
					String SkuSizCode = jObject.getString("SkuSizCode");
					String ItemStatus = jObject.getString("ItemStatus");
					String ReOrderLvl = jObject.getString("ReOrderLvl");
					String ReOrderQty = jObject.getString("ReOrderQty");
					String AvgPrice = jObject.getString("AvgPrice");
					String PurAcc = jObject.getString("PurAcc");
					String PurRetAcc = jObject.getString("PurRetAcc");
					String SVATAcc = jObject.getString("SVATAcc");
					String ExportAcc = jObject.getString("ExportAcc");
					String IndrExAcc = jObject.getString("IndrExAcc");
					String SalAcc = jObject.getString("SalAcc");
					String SalRetAcc = jObject.getString("SalRetAcc");
					String DisAcc = jObject.getString("DisAcc");
					String ClsStkAcc = jObject.getString("ClsStkAcc");
					String StkInAcc = jObject.getString("StkInAcc");
					String PrilCode = jObject.getString("PrilCode");
					String BrandCode = jObject.getString("BrandCode");
					String SBrandCode = jObject.getString("SBrandCode");
					String NOUCase = jObject.getString("NOUCase");
					String OrdSeq = jObject.getString("OrdSeq");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItems = new ContentValues();
					Cursor newrowfItemListuserrows = null;
					try {
						newrowfItemListuserrows = mydb.query(ITEMS, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (newrowfItemListuserrows == null) {
						newrowfItems.put("SKUCode", SKUCode.trim());
						newrowfItems.put("ItemCode", ItemCode.trim());
						newrowfItems.put("MapCode", MapCode.trim());
						newrowfItems.put("ItemName", ItemName.trim());
						newrowfItems.put("VenPcode", VenPcode.trim());
						newrowfItems.put("GroupCode", GroupCode.trim());
						newrowfItems.put("TypeCode", TypeCode.trim());
						newrowfItems.put("TaxComCode", TaxComCode.trim());
						newrowfItems.put("UnitCode", UnitCode.trim());
						newrowfItems.put("SkuSizCode", SkuSizCode.trim());
						newrowfItems.put("ItemStatus", ItemStatus.trim());
						newrowfItems.put("ReOrderLvl", ReOrderLvl.trim());
						newrowfItems.put("ReOrderQty", ReOrderQty.trim());
						newrowfItems.put("AvgPrice", AvgPrice.trim());
						newrowfItems.put("PurAcc", PurAcc.trim());
						newrowfItems.put("PurRetAcc", PurRetAcc.trim());
						newrowfItems.put("SVATAcc", SVATAcc.trim());
						newrowfItems.put("ExportAcc", ExportAcc.trim());
						newrowfItems.put("IndrExAcc", IndrExAcc.trim());
						newrowfItems.put("SalAcc", SalAcc.trim());
						newrowfItems.put("SalRetAcc", SalRetAcc.trim());
						newrowfItems.put("DisAcc", DisAcc.trim());
						newrowfItems.put("ClsStkAcc", ClsStkAcc.trim());
						newrowfItems.put("StkInAcc", StkInAcc.trim());
						newrowfItems.put("PrilCode", PrilCode.trim());
						newrowfItems.put("BrandCode", BrandCode.trim());
						newrowfItems.put("SBrandCode", SBrandCode.trim());
						newrowfItems.put("NOUCase", NOUCase.trim());
						newrowfItems.put("OrdSeq", OrdSeq.trim());
						newrowfItems.put("AddUser", AddUser.trim());
						newrowfItems.put("AddDatefitem", getCurrentTimeString()
								.toString());
						newrowfItems.put("AddMach", AddMach.trim());
						newrowfItems.put("RecordId", RecordId.trim());
						newrowfItems.put("timestamp_column ",
								getCurrentTimeString().toString());
						mydb.insert(ITEMS, null, newrowfItems);
						newrowfItemListuserrows.close();
						mydb.close();
					} else if (newrowfItemListuserrows.getCount() < 1) {
						newrowfItems.put("SKUCode", SKUCode.trim());
						newrowfItems.put("ItemCode", ItemCode.trim());
						newrowfItems.put("MapCode", MapCode.trim());
						newrowfItems.put("ItemName", ItemName.trim());
						newrowfItems.put("VenPcode", VenPcode.trim());
						newrowfItems.put("GroupCode", GroupCode.trim());
						newrowfItems.put("TypeCode", TypeCode.trim());
						newrowfItems.put("TaxComCode", TaxComCode.trim());
						newrowfItems.put("UnitCode", UnitCode.trim());
						newrowfItems.put("SkuSizCode", SkuSizCode.trim());
						newrowfItems.put("ItemStatus", ItemStatus.trim());
						newrowfItems.put("ReOrderLvl", ReOrderLvl.trim());
						newrowfItems.put("ReOrderQty", ReOrderQty.trim());
						newrowfItems.put("AvgPrice", AvgPrice.trim());
						newrowfItems.put("PurAcc", PurAcc.trim());
						newrowfItems.put("PurRetAcc", PurRetAcc.trim());
						newrowfItems.put("SVATAcc", SVATAcc.trim());
						newrowfItems.put("ExportAcc", ExportAcc.trim());
						newrowfItems.put("IndrExAcc", IndrExAcc.trim());
						newrowfItems.put("SalAcc", SalAcc.trim());
						newrowfItems.put("SalRetAcc", SalRetAcc.trim());
						newrowfItems.put("DisAcc", DisAcc.trim());
						newrowfItems.put("ClsStkAcc", ClsStkAcc.trim());
						newrowfItems.put("StkInAcc", StkInAcc.trim());
						newrowfItems.put("PrilCode", PrilCode.trim());
						newrowfItems.put("BrandCode", BrandCode.trim());
						newrowfItems.put("SBrandCode", SBrandCode.trim());
						newrowfItems.put("NOUCase", NOUCase.trim());
						newrowfItems.put("OrdSeq", OrdSeq.trim());
						newrowfItems.put("AddUser", AddUser.trim());
						newrowfItems.put("AddDatefitem", getCurrentTimeString()
								.toString());
						newrowfItems.put("AddMach", AddMach.trim());
						newrowfItems.put("RecordId", RecordId.trim());
						newrowfItems.put("timestamp_column ",
								getCurrentTimeString().toString());
						mydb.insert(ITEMS, null, newrowfItems);
						newrowfItemListuserrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfItems.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download Fdebtor**************

			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/Fdebtor/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerFdebtor = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFdebtor.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("FdebtorResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String DebCode = jObject.getString("DebCode");
					String DebName = jObject.getString("DebName");
					String DebAdd1 = jObject.getString("DebAdd1");
					String DebAdd2 = jObject.getString("DebAdd2");
					String DebAdd3 = jObject.getString("DebAdd3");
					String DebTele = jObject.getString("DebTele");
					String DebMob = jObject.getString("DebMob");
					String DebEMail = jObject.getString("DebEMail");
					String OutDis = jObject.getString("OutDis");
					String RemDis = jObject.getString("RemDis");
					String TownCode = jObject.getString("TownCode");
					String AreaCode = jObject.getString("AreaCode");
					String DebCatCode = jObject.getString("DebCatCode");
					String DbGrCode = jObject.getString("DbGrCode");
					String DebClsCode = jObject.getString("DebClsCode");
					String Status = jObject.getString("Status");
					String DebLylty = jObject.getString("DebLylty");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					String CrdPeriod = jObject.getString("CrdPeriod");
					String ChkCrdPrd = jObject.getString("ChkCrdPrd");
					String CrdLimit = jObject.getString("CrdLimit");
					String ChkCrdLmt = jObject.getString("ChkCrdLmt");
					String RepCode = jObject.getString("RepCode");
					String RankCode = jObject.getString("RankCode");
					String TranBatch = jObject.getString("TranBatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfdebtord = new ContentValues();
					Cursor fdebtorduserrows = null;
					try {
						fdebtorduserrows = mydb.query(ITEM_DEBTOR, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (fdebtorduserrows == null) {
						newrowfdebtord.put("DebCode", DebCode.trim());
						newrowfdebtord.put("DebName", DebName.trim());
						newrowfdebtord.put("DebAdd1", DebAdd1.trim());
						newrowfdebtord.put("DebAdd2", DebAdd2.trim());
						newrowfdebtord.put("DebAdd3", DebAdd3.trim());
						newrowfdebtord.put("DebTele", DebTele.trim());
						newrowfdebtord.put("DebMob", DebMob.trim());
						newrowfdebtord.put("DebEMail", DebEMail.trim());
						newrowfdebtord.put("CretDate", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("OutDis", OutDis.trim());
						newrowfdebtord.put("RemDis", RemDis.trim());
						newrowfdebtord.put("TownCode", TownCode.trim());
						newrowfdebtord.put("AreaCode", AreaCode.trim());
						newrowfdebtord.put("DebCatCode", DebCatCode.trim());
						newrowfdebtord.put("DbGrCode", DbGrCode.trim());
						newrowfdebtord.put("DebClsCode", DebClsCode.trim());
						newrowfdebtord.put("Status", Status.trim());
						newrowfdebtord.put("DebLylty", DebLylty.trim());
						newrowfdebtord.put("DealCode", DealCode.trim());
						newrowfdebtord.put("AddUser", AddUser.trim());
						newrowfdebtord.put("AddDateDEB", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("AddMach", AddMach.trim());
						newrowfdebtord.put("RecordId", RecordId.trim());
						newrowfdebtord.put("timestamp_column",
								getCurrentTimeString().toString());
						newrowfdebtord.put("CrdPeriod", CrdPeriod.trim());
						newrowfdebtord.put("ChkCrdPrd", ChkCrdPrd.trim());
						newrowfdebtord.put("CrdLimit", CrdLimit.trim());
						newrowfdebtord.put("ChkCrdLmt", ChkCrdLmt.trim());
						newrowfdebtord.put("RepCode", RepCode.trim());
						newrowfdebtord.put("RankCode", RankCode.trim());
						newrowfdebtord.put("txndate", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("TranBatch", TranBatch.trim());
						mydb.insert(ITEM_DEBTOR, null, newrowfdebtord);
						fdebtorduserrows.close();
						mydb.close();
					} else if (fdebtorduserrows.getCount() < 1) {
						newrowfdebtord.put("DebCode", DebCode.trim());
						newrowfdebtord.put("DebName", DebName.trim());
						newrowfdebtord.put("DebAdd1", DebAdd1.trim());
						newrowfdebtord.put("DebAdd2", DebAdd2.trim());
						newrowfdebtord.put("DebAdd3", DebAdd3.trim());
						newrowfdebtord.put("DebTele", DebTele.trim());
						newrowfdebtord.put("DebMob", DebMob.trim());
						newrowfdebtord.put("DebEMail", DebEMail.trim());
						newrowfdebtord.put("CretDate", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("OutDis", OutDis.trim());
						newrowfdebtord.put("RemDis", RemDis.trim());
						newrowfdebtord.put("TownCode", TownCode.trim());
						newrowfdebtord.put("AreaCode", AreaCode.trim());
						newrowfdebtord.put("DebCatCode", DebCatCode.trim());
						newrowfdebtord.put("DbGrCode", DbGrCode.trim());
						newrowfdebtord.put("DebClsCode", DebClsCode.trim());
						newrowfdebtord.put("Status", Status.trim());
						newrowfdebtord.put("DebLylty", DebLylty.trim());
						newrowfdebtord.put("DealCode", DealCode.trim());
						newrowfdebtord.put("AddUser", AddUser.trim());
						newrowfdebtord.put("AddDateDEB", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("AddMach", AddMach.trim());
						newrowfdebtord.put("RecordId", RecordId.trim());
						newrowfdebtord.put("timestamp_column",
								getCurrentTimeString().toString());
						newrowfdebtord.put("CrdPeriod", CrdPeriod.trim());
						newrowfdebtord.put("ChkCrdPrd", ChkCrdPrd.trim());
						newrowfdebtord.put("CrdLimit", CrdLimit.trim());
						newrowfdebtord.put("ChkCrdLmt", ChkCrdLmt.trim());
						newrowfdebtord.put("RepCode", RepCode.trim());
						newrowfdebtord.put("RankCode", RankCode.trim());
						newrowfdebtord.put("txndate", getCurrentTimeString()
								.toString());
						newrowfdebtord.put("TranBatch", TranBatch.trim());
						mydb.insert(ITEM_DEBTOR, null, newrowfdebtord);
						fdebtorduserrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerFdebtor.close();

			} catch (Exception e) {
				// Toast.makeText(this, evtoString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fControl**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fControl/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfControl = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfControl.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fControlResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String ComName = jObject.getString("ComName");
					String ComAdd1 = jObject.getString("ComAdd1");
					String ComAdd2 = jObject.getString("ComAdd2");
					String ComAdd3 = jObject.getString("ComAdd3");
					String comtel1 = jObject.getString("comtel1");
					String comtel2 = jObject.getString("comtel2");
					String comfax1 = jObject.getString("comfax1");
					String comemail = jObject.getString("comemail");
					String comweb = jObject.getString("comweb");
					// String confyear = jObject.getString("confyear");
					// String contyear = jObject.getString("contyear");
					String comRegNo = jObject.getString("comRegNo");
					// String ConfTxn = jObject.getString("ConfTxn");
					// String ContTxn = jObject.getString("ContTxn");
					String Crystalpath = jObject.getString("Crystalpath");
					String VatCmTaxNo = jObject.getString("VatCmTaxNo");
					String NbtCmTaxNo = jObject.getString("NbtCmTaxNo");
					String SysId = jObject.getString("SysId");
					String DealCode = jObject.getString("DealCode");
					String basecur = jObject.getString("basecur");
					String BalgCrLm = jObject.getString("BalgCrLm");
					String conage1 = jObject.getString("conage1");
					String conage2 = jObject.getString("conage2");
					String conage3 = jObject.getString("conage3");
					String conage4 = jObject.getString("conage4");
					String conage5 = jObject.getString("conage5");
					String conage6 = jObject.getString("conage6");
					String conage7 = jObject.getString("conage7");
					String conage8 = jObject.getString("conage8");
					String conage9 = jObject.getString("conage9");
					String conage10 = jObject.getString("conage10");
					String conage11 = jObject.getString("conage11");
					String conage12 = jObject.getString("conage12");
					String conage13 = jObject.getString("conage13");
					String conage14 = jObject.getString("conage14");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfcontrol = new ContentValues();
					Cursor fcontroluserrows = null;
					try {
						fcontroluserrows = mydb.query(ITEM_CONTROL, null,
								"fcontrol_id ='" + SysId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (fcontroluserrows == null) {
						newrowfcontrol.put("ComName", ComName.trim());
						newrowfcontrol.put("ComAdd1", ComAdd1.trim());
						newrowfcontrol.put("ComAdd2", ComAdd2.trim());
						newrowfcontrol.put("ComAdd3", ComAdd3.trim());
						newrowfcontrol.put("comtel1", comtel1.trim());
						newrowfcontrol.put("comtel2", comtel2.trim());
						newrowfcontrol.put("comfax1", comfax1.trim());
						newrowfcontrol.put("comemail", comemail.trim());
						newrowfcontrol.put("comweb", comweb.trim());
						newrowfcontrol.put("confyear", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("contyear", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("comRegNo", comRegNo.trim());
						newrowfcontrol.put("ConfTxn", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("ContTxn", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("Crystalpath", Crystalpath.trim());
						newrowfcontrol.put("VatCmTaxNo", VatCmTaxNo.trim());
						newrowfcontrol.put("NbtCmTaxNo", NbtCmTaxNo.trim());
						newrowfcontrol.put("SysId", SysId.trim());
						newrowfcontrol.put("DealCode", DealCode.trim());
						newrowfcontrol.put("basecur", basecur.trim());
						newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
						newrowfcontrol.put("conage1", conage1.trim());
						newrowfcontrol.put("conage2", conage2.trim());
						newrowfcontrol.put("conage3", conage3.trim());
						newrowfcontrol.put("conage4", conage4.trim());
						newrowfcontrol.put("conage5", conage5.trim());
						newrowfcontrol.put("conage6", conage6.trim());
						newrowfcontrol.put("conage7", conage7.trim());
						newrowfcontrol.put("conage8", conage8.trim());
						newrowfcontrol.put("conage9", conage9.trim());
						newrowfcontrol.put("conage10", conage10.trim());
						newrowfcontrol.put("conage11", conage11.trim());
						newrowfcontrol.put("conage12", conage12.trim());
						newrowfcontrol.put("conage13", conage13.trim());
						newrowfcontrol.put("conage14", conage14.trim());
						mydb.insert(ITEM_CONTROL, null, newrowfcontrol);
						fcontroluserrows.close();
						mydb.close();
					} else if (fcontroluserrows.getCount() < 1) {
						newrowfcontrol.put("ComName", ComName.trim());
						newrowfcontrol.put("ComAdd1", ComAdd1.trim());
						newrowfcontrol.put("ComAdd2", ComAdd2.trim());
						newrowfcontrol.put("ComAdd3", ComAdd3.trim());
						newrowfcontrol.put("comtel1", comtel1.trim());
						newrowfcontrol.put("comtel2", comtel2.trim());
						newrowfcontrol.put("comfax1", comfax1.trim());
						newrowfcontrol.put("comemail", comemail.trim());
						newrowfcontrol.put("comweb", comweb.trim());
						newrowfcontrol.put("confyear", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("contyear", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("comRegNo", comRegNo.trim());
						newrowfcontrol.put("ConfTxn", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("ContTxn", getCurrentTimeString()
								.toString());
						newrowfcontrol.put("Crystalpath", Crystalpath.trim());
						newrowfcontrol.put("VatCmTaxNo", VatCmTaxNo.trim());
						newrowfcontrol.put("NbtCmTaxNo", NbtCmTaxNo.trim());
						newrowfcontrol.put("SysId", SysId.trim());
						newrowfcontrol.put("DealCode", DealCode.trim());
						newrowfcontrol.put("basecur", basecur.trim());
						newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
						newrowfcontrol.put("conage1", conage1.trim());
						newrowfcontrol.put("conage2", conage2.trim());
						newrowfcontrol.put("conage3", conage3.trim());
						newrowfcontrol.put("conage4", conage4.trim());
						newrowfcontrol.put("conage5", conage5.trim());
						newrowfcontrol.put("conage6", conage6.trim());
						newrowfcontrol.put("conage7", conage7.trim());
						newrowfcontrol.put("conage8", conage8.trim());
						newrowfcontrol.put("conage9", conage9.trim());
						newrowfcontrol.put("conage10", conage10.trim());
						newrowfcontrol.put("conage11", conage11.trim());
						newrowfcontrol.put("conage12", conage12.trim());
						newrowfcontrol.put("conage13", conage13.trim());
						newrowfcontrol.put("conage14", conage14.trim());
						mydb.insert(ITEM_CONTROL, null, newrowfcontrol);
						fcontroluserrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfControl.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fCompanySetting**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fCompanySetting/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanySetting = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanySetting.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fCompanySettingResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String cSettingsCode = jObject.getString("cSettingsCode");
					String cSettingGrp = jObject.getString("cSettingGrp");
					String cLocationChar = jObject.getString("cLocationChar");
					String cCharVal = jObject.getString("cCharVal");
					String nNumVal = jObject.getString("nNumVal");
					String cRemarks = jObject.getString("cRemarks");
					String nType = jObject.getString("nType");
					String bUpdateFlag = jObject.getString("bUpdateFlag");
					String cCompanyCode = jObject.getString("cCompanyCode");
					String recordid = jObject.getString("recordid");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfCompanySetting = new ContentValues();
					Cursor fCompanySettingrows = null;
					try {
						fCompanySettingrows = mydb.query(ITEM_COMPANY_SETTING,
								null, "fcomset_id ='" + recordid + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fCompanySettingrows == null) {
						newrowfCompanySetting.put("cSettingsCode",
								cSettingsCode.trim());
						newrowfCompanySetting.put("cSettingGrp",
								cSettingGrp.trim());
						newrowfCompanySetting.put("cLocationChar",
								cLocationChar.trim());
						newrowfCompanySetting.put("cCharVal", cCharVal.trim());
						newrowfCompanySetting.put("nNumVal", nNumVal.trim());
						newrowfCompanySetting.put("cRemarks", cRemarks.trim());
						newrowfCompanySetting.put("nType ", nType.trim());
						newrowfCompanySetting.put("bUpdateFlag",
								bUpdateFlag.trim());
						newrowfCompanySetting.put("cCompanyCode",
								cCompanyCode.trim());
						newrowfCompanySetting.put("recordid", recordid.trim());
						newrowfCompanySetting.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_COMPANY_SETTING, null,
								newrowfCompanySetting);
						fCompanySettingrows.close();
						mydb.close();
					} else if (fCompanySettingrows.getCount() < 1) {
						newrowfCompanySetting.put("cSettingsCode",
								cSettingsCode.trim());
						newrowfCompanySetting.put("cSettingGrp",
								cSettingGrp.trim());
						newrowfCompanySetting.put("cLocationChar",
								cLocationChar.trim());
						newrowfCompanySetting.put("cCharVal", cCharVal.trim());
						newrowfCompanySetting.put("nNumVal", nNumVal.trim());
						newrowfCompanySetting.put("cRemarks", cRemarks.trim());
						newrowfCompanySetting.put("nType ", nType.trim());
						newrowfCompanySetting.put("bUpdateFlag",
								bUpdateFlag.trim());
						newrowfCompanySetting.put("cCompanyCode",
								cCompanyCode.trim());
						newrowfCompanySetting.put("recordid", recordid.trim());
						newrowfCompanySetting.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_COMPANY_SETTING, null,
								newrowfCompanySetting);
						fCompanySettingrows.close();
						mydb.close();
					}
					mydb.close();

				}

				readerfCompanySetting.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fArea**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fArea/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfArea = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfArea.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse.getJSONArray("fAreaResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					// String fAreaID = jObject.getString("fAreaID");
					String AreaCode = jObject.getString("AreaCode");
					String AreaName = jObject.getString("AreaName");
					String RegCode = jObject.getString("RegCode");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					// String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					// String timestamp_column =
					// jObject.getString("timestamp_column");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfArea = new ContentValues();
					Cursor fArearows = null;
					try {
						fArearows = mydb.query(ITEM_AREA, null, "RecordId ='"
								+ RecordId + "'", null, null, null, null);
					} catch (Exception e) {
					}
					if (fArearows == null) {
						newrowfArea.put("AreaCode", AreaCode.trim());
						newrowfArea.put("AreaName", AreaName.trim());
						newrowfArea.put("RegCode", RegCode.trim());
						newrowfArea.put("DealCode", DealCode.trim());
						newrowfArea.put("AddUser", AddUser.trim());
						newrowfArea.put("AddDatefarea", getCurrentTimeString()
								.toString());
						newrowfArea.put("AddMach", AddMach.trim());
						newrowfArea.put("RecordId", RecordId.trim());
						newrowfArea.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_AREA, null, newrowfArea);
						fArearows.close();
						mydb.close();
					} else if (fArearows.getCount() < 1) {
						newrowfArea.put("AreaCode", AreaCode.trim());
						newrowfArea.put("AreaName", AreaName.trim());
						newrowfArea.put("RegCode", RegCode.trim());
						newrowfArea.put("DealCode", DealCode.trim());
						newrowfArea.put("AddUser", AddUser.trim());
						newrowfArea.put("AddDatefarea", getCurrentTimeString()
								.toString());
						newrowfArea.put("AddMach", AddMach.trim());
						newrowfArea.put("RecordId", RecordId.trim());
						newrowfArea.put("timestamp_column",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_AREA, null, newrowfArea);
						fArearows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfArea.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fLocations**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fLocations/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfLocations = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfLocations.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fLocationsResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Address1 = jObject.getString("Address1");
					String Address2 = jObject.getString("Address2");
					String Address3 = jObject.getString("Address3");
					String Contact = jObject.getString("Contact");
					String EMail = jObject.getString("EMail");
					String FaxNo = jObject.getString("FaxNo");
					String LocCode = jObject.getString("LocCode");
					String LocName = jObject.getString("LocName");
					String LoctCode = jObject.getString("LoctCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String TeleNo = jObject.getString("TeleNo");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowflocation = new ContentValues();
					Cursor newrowflocationrows = null;
					try {
						newrowflocationrows = mydb.query(ITEM_LOCATION, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (newrowflocationrows == null) {
						newrowflocation.put("AddMach", AddMach.trim());
						newrowflocation.put("AddUser", AddUser.trim());
						newrowflocation.put("Address1", Address1.trim());
						newrowflocation.put("Address2", Address2.trim());
						newrowflocation.put("Address3", Address3.trim());
						newrowflocation.put("Contact", Contact.trim());
						newrowflocation.put("EMail", EMail.trim());
						newrowflocation.put("FaxNo", FaxNo.trim());
						newrowflocation.put("LocCode", LocCode.trim());
						newrowflocation.put("LocName", LocName.trim());
						newrowflocation.put("LoctCode", LoctCode.trim());
						newrowflocation.put("RecordId", RecordId.trim());
						newrowflocation.put("RepCode", RepCode.trim());
						newrowflocation.put("TeleNo", TeleNo.trim());
						newrowflocation.put("LocAddDate",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_LOCATION, null, newrowflocation);
						newrowflocationrows.close();
						mydb.close();
					} else if (newrowflocationrows.getCount() < 1) {
						newrowflocation.put("AddMach", AddMach.trim());
						newrowflocation.put("AddUser", AddUser.trim());
						newrowflocation.put("Address1", Address1.trim());
						newrowflocation.put("Address2", Address2.trim());
						newrowflocation.put("Address3", Address3.trim());
						newrowflocation.put("Contact", Contact.trim());
						newrowflocation.put("EMail", EMail.trim());
						newrowflocation.put("FaxNo", FaxNo.trim());
						newrowflocation.put("LocCode", LocCode.trim());
						newrowflocation.put("LocName", LocName.trim());
						newrowflocation.put("LoctCode", LoctCode.trim());
						newrowflocation.put("RecordId", RecordId.trim());
						newrowflocation.put("RepCode", RepCode.trim());
						newrowflocation.put("TeleNo", TeleNo.trim());
						newrowflocation.put("LocAddDate",
								getCurrentTimeString().toString());
						mydb.insert(ITEM_LOCATION, null, newrowflocation);
						newrowflocationrows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfLocations.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FCompanyBranch**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/FCompanyBranch/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanyBranchResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanyBranchResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("FCompanyBranchResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String BranchCode = jObject.getString("BranchCode");
					String RecordId = jObject.getString("RecordId");
					String cSettingsCode = jObject.getString("cSettingsCode");
					String nNumVal = jObject.getString("nNumVal");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfRepbranchrows = new ContentValues();
					Cursor newrowflRebranchprows = null;
					try {
						newrowflRebranchprows = mydb.query(INV_COMPANY_BRANCH,
								null, "RecordId ='" + RecordId + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowflRebranchprows == null) {
						newrowreaderfRepbranchrows.put("BranchCode",
								BranchCode.trim());
						newrowreaderfRepbranchrows.put("RecordId",
								RecordId.trim());
						newrowreaderfRepbranchrows.put("cSettingsCode",
								cSettingsCode.trim());
						newrowreaderfRepbranchrows.put("nNumVal",
								nNumVal.trim());

						mydb.insert(INV_COMPANY_BRANCH, null,
								newrowreaderfRepbranchrows);
						newrowflRebranchprows.close();
						mydb.close();
					} else if (newrowflRebranchprows.getCount() < 1) {
						newrowreaderfRepbranchrows.put("BranchCode",
								BranchCode.trim());
						newrowreaderfRepbranchrows.put("RecordId",
								RecordId.trim());
						newrowreaderfRepbranchrows.put("cSettingsCode",
								cSettingsCode.trim());
						newrowreaderfRepbranchrows.put("nNumVal",
								nNumVal.trim());

						mydb.insert(INV_COMPANY_BRANCH, null,
								newrowreaderfRepbranchrows);
						newrowflRebranchprows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfCompanyBranchResult.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fSalRep**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/fSalRep/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfSalRepResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfSalRepResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fSalRepResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String ASECode = jObject.getString("ASECode");
					String AreaCode = jObject.getString("AreaCode");
					String DealCode = jObject.getString("DealCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String RepPrefix = jObject.getString("RepPrefix");
					String RepTCode = jObject.getString("RepTCode");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfSalReprows = new ContentValues();
					Cursor newrowfSalReprows = null;
					try {
						newrowfSalReprows = mydb.query(INV_SAL_REP, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (newrowfSalReprows == null) {
						newrowreaderfSalReprows.put("ASECode", ASECode.trim());
						newrowreaderfSalReprows
								.put("AreaCode", AreaCode.trim());
						newrowreaderfSalReprows
								.put("DealCode", DealCode.trim());
						newrowreaderfSalReprows
								.put("RecordId", RecordId.trim());
						newrowreaderfSalReprows.put("RepCode", RepCode.trim());
						newrowreaderfSalReprows.put("RepPrefix",
								RepPrefix.trim());
						newrowreaderfSalReprows
								.put("RepTCode", RepTCode.trim());

						mydb.insert(INV_SAL_REP, null, newrowreaderfSalReprows);
						newrowfSalReprows.close();
						mydb.close();
					} else if (newrowfSalReprows.getCount() < 1) {
						newrowreaderfSalReprows.put("ASECode", ASECode.trim());
						newrowreaderfSalReprows
								.put("AreaCode", AreaCode.trim());
						newrowreaderfSalReprows
								.put("DealCode", DealCode.trim());
						newrowreaderfSalReprows
								.put("RecordId", RecordId.trim());
						newrowreaderfSalReprows.put("RepCode", RepCode.trim());
						newrowreaderfSalReprows.put("RepPrefix",
								RepPrefix.trim());
						newrowreaderfSalReprows
								.put("RepTCode", RepTCode.trim());

						mydb.insert(INV_SAL_REP, null, newrowreaderfSalReprows);
						newrowfSalReprows.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfSalRepResult.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download FOrdHed**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/FOrdHed/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfstordhed = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstordhed.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("FOrdHedResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String AreaCode = jObject.getString("AreaCode");
					String CostCode = jObject.getString("CostCode");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DealCode = jObject.getString("DealCode");
					String DebCode = jObject.getString("DebCode");
					String InvAmt = jObject.getString("InvAmt");
					String InvDis = jObject.getString("InvDis");
					String InvFlg = jObject.getString("InvFlg");
					String LocCode = jObject.getString("LocCode");
					String ManuRef = jObject.getString("ManuRef");
					String OutDis = jObject.getString("OutDis");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String TotMkrAmt = jObject.getString("TotMkrAmt");
					String TotalAmt = jObject.getString("TotalAmt");
					String TotalDis = jObject.getString("TotalDis");
					String TranBatch = jObject.getString("TranBatch");
					String TxnType = jObject.getString("TxnType");
					String UnOvAmt = jObject.getString("UnOvAmt");
					String prtcopy = jObject.getString("prtcopy");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstordhed = new ContentValues();
					Cursor cursorfstordhed = null;
					try {
						cursorfstordhed = mydb.query(STOCK_ORDER_HEAD, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (cursorfstordhed == null) {
						newrowfstordhed.put("AddMach", AddMach.trim());
						newrowfstordhed.put("AddUser", AddUser.trim());
						newrowfstordhed.put("AreaCode", AreaCode.trim());
						newrowfstordhed.put("CostCode", CostCode.trim());
						newrowfstordhed.put("CurCode", CurCode.trim());
						newrowfstordhed.put("CurRate", CurRate.trim());
						newrowfstordhed.put("DealCode", DealCode.trim());
						newrowfstordhed.put("DebCode", DebCode.trim());
						newrowfstordhed.put("InvAmt", InvAmt.trim());
						newrowfstordhed.put("InvDis", InvDis.trim());
						newrowfstordhed.put("InvFlg", InvFlg.trim());
						newrowfstordhed.put("LocCode", LocCode.trim());
						newrowfstordhed.put("ManuRef", ManuRef.trim());
						newrowfstordhed.put("OutDis", OutDis.trim());
						newrowfstordhed.put("RecordId", RecordId.trim());
						newrowfstordhed.put("RefNo", RefNo.trim());
						newrowfstordhed.put("Remarks", Remarks.trim());
						newrowfstordhed.put("RepCode", RepCode.trim());
						newrowfstordhed.put("RouteCode", RouteCode.trim());
						newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
						newrowfstordhed.put("TotalAmt", TotalAmt.trim());
						newrowfstordhed.put("TotalDis", TotalDis.trim());
						newrowfstordhed.put("TranBatch", TranBatch.trim());
						newrowfstordhed.put("TxnType", TxnType.trim());
						newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
						newrowfstordhed.put("prtcopy", prtcopy.trim());
						newrowfstordhed.put("TxnDate", TxnDate.trim());
						newrowfstordhed.put("stOrderComplete", "0");
						mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
						cursorfstordhed.close();
						mydb.close();
					} else if (cursorfstordhed.getCount() < 1) {
						newrowfstordhed.put("AddMach", AddMach.trim());
						newrowfstordhed.put("AddUser", AddUser.trim());
						newrowfstordhed.put("AreaCode", AreaCode.trim());
						newrowfstordhed.put("CostCode", CostCode.trim());
						newrowfstordhed.put("CurCode", CurCode.trim());
						newrowfstordhed.put("CurRate", CurRate.trim());
						newrowfstordhed.put("DealCode", DealCode.trim());
						newrowfstordhed.put("DebCode", DebCode.trim());
						newrowfstordhed.put("InvAmt", InvAmt.trim());
						newrowfstordhed.put("InvDis", InvDis.trim());
						newrowfstordhed.put("InvFlg", InvFlg.trim());
						newrowfstordhed.put("LocCode", LocCode.trim());
						newrowfstordhed.put("ManuRef", ManuRef.trim());
						newrowfstordhed.put("OutDis", OutDis.trim());
						newrowfstordhed.put("RecordId", RecordId.trim());
						newrowfstordhed.put("RefNo", RefNo.trim());
						newrowfstordhed.put("Remarks", Remarks.trim());
						newrowfstordhed.put("RepCode", RepCode.trim());
						newrowfstordhed.put("RouteCode", RouteCode.trim());
						newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
						newrowfstordhed.put("TotalAmt", TotalAmt.trim());
						newrowfstordhed.put("TotalDis", TotalDis.trim());
						newrowfstordhed.put("TranBatch", TranBatch.trim());
						newrowfstordhed.put("TxnType", TxnType.trim());
						newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
						newrowfstordhed.put("prtcopy", prtcopy.trim());
						newrowfstordhed.put("TxnDate", TxnDate.trim());
						newrowfstordhed.put("stOrderComplete", "0");
						mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
						cursorfstordhed.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfstordhed.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FOrddet**************
			try {
				// Replace it with your own WCF service path
				URL json = new URL(
						"http://220.247.242.201/PDADBWebService/PDADBWebServiceRest.svc/FOrddet/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfstorddet = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstorddet.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("FOrddetResult");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BDisAmt = jObject.getString("BDisAmt");
					String BSellPrice = jObject.getString("BSellPrice");
					String BTSellPrice = jObject.getString("BTSellPrice");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String BalQty = jObject.getString("BalQty");
					String CaseQty = jObject.getString("CaseQty");
					String CostPrice = jObject.getString("CostPrice");
					String DisAmt = jObject.getString("DisAmt");
					String DisPer = jObject.getString("DisPer");
					String Itemcode = jObject.getString("Itemcode");
					String PiceQty = jObject.getString("PiceQty");
					String Qty = jObject.getString("Qty");
					String ReaCode = jObject.getString("ReaCode");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String SellPrice = jObject.getString("SellPrice");
					String SeqNo = jObject.getString("SeqNo");
					String TSellPrice = jObject.getString("TSellPrice");
					String TaxAmt = jObject.getString("TaxAmt");
					String TxnType = jObject.getString("TxnType");
					String Txnseqno = jObject.getString("Txnseqno");
					String Type = jObject.getString("Type");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstorddet = new ContentValues();
					Cursor cursorfstorddet = null;
					try {
						cursorfstorddet = mydb.query(STOCK_ORDER_DETAIL, null,
								"RecordId ='" + RecordId + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (cursorfstorddet == null) {
						newrowfstorddet.put("Amt", Amt.trim());
						newrowfstorddet.put("BAmt", BAmt.trim());
						newrowfstorddet.put("BDisAmt", BDisAmt.trim());
						newrowfstorddet.put("BSellPrice", BSellPrice.trim());
						newrowfstorddet.put("BTSellPrice", BTSellPrice.trim());
						newrowfstorddet.put("BTaxAmt", BTaxAmt.trim());
						newrowfstorddet.put("BalQty", BalQty.trim());
						newrowfstorddet.put("CaseQty", CaseQty.trim());
						newrowfstorddet.put("CostPrice", CostPrice.trim());
						newrowfstorddet.put("DisAmt", DisAmt.trim());
						newrowfstorddet.put("DisPer", DisPer.trim());
						newrowfstorddet.put("Itemcode", Itemcode.trim());
						newrowfstorddet.put("PiceQty", PiceQty.trim());
						newrowfstorddet.put("Qty", Qty.trim());
						newrowfstorddet.put("ReaCode", ReaCode.trim());
						newrowfstorddet.put("RecordId", RecordId.trim());
						newrowfstorddet.put("RefNo", RefNo.trim());
						newrowfstorddet.put("SellPrice", SellPrice.trim());
						newrowfstorddet.put("SeqNo", SeqNo.trim());
						newrowfstorddet.put("TSellPrice", TSellPrice.trim());
						newrowfstorddet.put("TaxAmt", TaxAmt.trim());
						newrowfstorddet.put("TxnType", TxnType.trim());
						newrowfstorddet.put("Txnseqno", Txnseqno.trim());
						newrowfstorddet.put("Type", Type.trim());
						newrowfstorddet.put("TxnDate", TxnDate.trim());
						mydb.insert(STOCK_ORDER_DETAIL, null, newrowfstorddet);
						cursorfstorddet.close();
						mydb.close();
					} else if (cursorfstorddet.getCount() < 1) {
						newrowfstorddet.put("Amt", Amt.trim());
						newrowfstorddet.put("BAmt", BAmt.trim());
						newrowfstorddet.put("BDisAmt", BDisAmt.trim());
						newrowfstorddet.put("BSellPrice", BSellPrice.trim());
						newrowfstorddet.put("BTSellPrice", BTSellPrice.trim());
						newrowfstorddet.put("BTaxAmt", BTaxAmt.trim());
						newrowfstorddet.put("BalQty", BalQty.trim());
						newrowfstorddet.put("CaseQty", CaseQty.trim());
						newrowfstorddet.put("CostPrice", CostPrice.trim());
						newrowfstorddet.put("DisAmt", DisAmt.trim());
						newrowfstorddet.put("DisPer", DisPer.trim());
						newrowfstorddet.put("Itemcode", Itemcode.trim());
						newrowfstorddet.put("PiceQty", PiceQty.trim());
						newrowfstorddet.put("Qty", Qty.trim());
						newrowfstorddet.put("ReaCode", ReaCode.trim());
						newrowfstorddet.put("RecordId", RecordId.trim());
						newrowfstorddet.put("RefNo", RefNo.trim());
						newrowfstorddet.put("SellPrice", SellPrice.trim());
						newrowfstorddet.put("SeqNo", SeqNo.trim());
						newrowfstorddet.put("TSellPrice", TSellPrice.trim());
						newrowfstorddet.put("TaxAmt", TaxAmt.trim());
						newrowfstorddet.put("TxnType", TxnType.trim());
						newrowfstorddet.put("Txnseqno", Txnseqno.trim());
						newrowfstorddet.put("Type", Type.trim());
						newrowfstorddet.put("TxnDate", TxnDate.trim());
						mydb.insert(STOCK_ORDER_DETAIL, null, newrowfstorddet);
						cursorfstorddet.close();
						mydb.close();
					}
					mydb.close();
				}

				readerfstorddet.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			mydb.close();
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			Intent intentLogin = new Intent(getBaseContext(),
					DM_InvoiceMainActivity.class);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentLogin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentLogin);
			finish();
			return;

		}

	}

	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

}
